<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/5 0005
 * Time: 下午 1:50
 */

namespace App\Http\Classes;


use Illuminate\Support\Facades\Redis;

class Phone
{
    private $phone;
    private $code;
    private $isLock = false;

    private $prefix = [
        'register' => 'p_register_',
        'reset'    => 'p_reset_',
        'lock'     => 'p_lock_',
    ];

    private $lockKey;
    private $registerKey;
    private $resetKey;

//    private $Api = 'http://api.sms.cn/sms/';
    private $Api = 'http://sms.market.alicloudapi.com/singleSendSms';
    private $Uid = 'grey';
    private $AppSecret = '6f59816e0c8cdfb78622388559439800';
    private $RegisterTemplate = 405164;
    private $ResetTemplate = 100003;
    private $Response = null;

    private $error = 0;
    private $message = array(
          0 => '请勿频繁操作',
        100 => '发送成功',
        101 => '验证失败',
        102 => '短信不足',
        103 => '操作失败',
        104 => '非法字符',
        105 => '内容过多',
        106 => '号码过多',
        108 => '号码内容空',
        112 => '号码错误',
        113 => '定时时间格式不对',
        116 => '禁止接口发送',
        117 => '绑定IP不正确',
        161 => '未添加短信模板',
        162 => '模板格式不正确',
        163 => '模板ID不正确',
        164 => '全文模板不匹配'
    );

    public function __construct( $phone = '', $isValid = false )
    {
        $this->phone = $phone;
        $this->setKeys();
        if ( $isValid )
        {
            $this->validatorLock();
        }
    }

    private function setKeys()
    {
        $this->lockKey      = $this->prefix['lock'] . $this->phone;
        $this->registerKey  = $this->prefix['register'] . $this->phone;
        $this->resetKey     = $this->prefix['reset'] . $this->phone;
    }

    private function validatorLock()
    {
        if ( Redis::exists( $this->lockKey ) )
        {
            $this->isLock = true;
        }
        else
        {
            $this->isLock = false;
        }
    }

    public function validatorRegisterCode( $code )
    {
        $this->getRegisterCode();
        if ( $code == $this->code )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function validatorResetCode( $code )
    {
        $this->getResetCode();
        if ( $code == $this->code )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private function getRegisterCode()
    {
        $this->code = Redis::get($this->registerKey);
    }

    private function getResetCode()
    {
        $this->code = Redis::get($this->resetKey);
    }

    private function addLock()
    {
        Redis::set( $this->lockKey, true );
        Redis::expire( $this->lockKey, 60 );
    }

    private function createCode()
    {
        $this->code = Common::getRand();
    }

    private function saveRegisterCode()
    {
        Redis::set( $this->registerKey, $this->code );
        Redis::expire( $this->registerKey, 1800 );
    }

    private function saveResetCode()
    {
        Redis::set( $this->resetKey, $this->code );
        Redis::expire( $this->resetKey, 1800 );
    }

    public function getPhone()
    {
        return $this->phone;
    }

    public function getLock()
    {
        return $this->isLock;
    }

    public function isLock()
    {
        Redis::get();
    }

    public function sendRegisterCode()
    {
        if ( ! $this->isLock )
        {
            $this->createCode();
            $this->saveRegisterCode();
            $this->Response = $this->postRequest( $this->Api, array(
                'ac'        => 'send',
                'uid'       => $this->Uid,
                'pwd'       => $this->AppSecret,
                'template'  => $this->RegisterTemplate,
                'mobile'    => $this->phone,
                'content'   => json_encode(array('code' => $this->code )))
            );
            $this->Response = mb_convert_encoding($this->Response, 'UTF-8', 'GBK');
            $this->Response = (array)json_decode($this->Response);
            if ( $this->Response['stat'] == 100 )
            {
                $this->addLock();
                return true;
            }
            else
            {
                $this->error = $this->Response['stat'];
                return false;
            }
        }
        else
        {
            $this->error = 0;
            return false;
        }
    }

    public function sendResetCode()
    {
        if ( ! $this->isLock )
        {
            $this->createCode();
            $this->saveResetCode();
            $this->Response = $this->postRequest( $this->Api, array(
                'ac'        => 'send',
                'uid'       => $this->Uid,
                'pwd'       => $this->AppSecret,
                'template'  => $this->ResetTemplate,
                'mobile'    => $this->phone,
                'content'   => json_encode(array('code' => $this->code, 'product' => '英语小网站' )))
            );
            $this->Response = mb_convert_encoding($this->Response, 'UTF-8', 'GBK');
            $this->Response = (array)json_decode($this->Response);
            if ( $this->Response['stat'] == 100 )
            {
                $this->addLock();
                return true;
            }
            else
            {
                $this->error = $this->Response['stat'];
                return false;
            }
        }
        else
        {
            $this->error = 0;
            return false;
        }
    }

    public function getResponse()
    {
        return $this->Response;
    }

    public function getMessage()
    {
        return $this->message[ $this->error ];
    }

    public function test()
    {
        $api = 'https://webapi.sms.mob.com';
        $appkey = '1f2b1f847b63e';

        // 发送验证码
        $response = $this->postRequest( $api . '/sms/verify', array(
	        'appkey' => $appkey,
            'phone' => '18408248050',
            'zone' => '86',
	        'code' => '1234',
            )
        );

        return $response;
    }

    /**
     * 发起一个post请求到指定接口
     *
     * @param string $api 请求的接口
     * @param array $params post参数
     * @param int $timeout 超时时间
     * @return string 请求结果
     */
    private function postRequest( $api, array $params = array(), $timeout = 30 )
    {
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $api );
        // 以返回的形式接收信息
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        // 设置为POST方式
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params ) );
        // 不验证https证书
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
        curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
            'Accept: application/json',
        ) );
        // 发送数据
        $response = curl_exec( $ch );
        // 不要忘记释放资源
        curl_close( $ch );
        return $response;
    }

    public function aliyunSMS()
    {
        $host = "http://sms.market.alicloudapi.com";
        $path = "/singleSendSms";
        $method = "GET";
        $appcode = "339cf34e56ec48c4b8414319e3806181";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = 'ParamString={"code":"123456"}&RecNum=' . $this->phone . '&SignName=英语学习&TemplateCode=SMS_100880029';
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $response = curl_exec($curl);
        curl_close( $curl );
        return $response;
    }

    public function aliyunTest()
    {
        $host = "http://sms.market.alicloudapi.com";
        $path = "/singleSendSms";
        $method = "GET";
        $appcode = "339cf34e56ec48c4b8414319e3806181";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "ParamString=%7B%22no%22%3A%22123456%22%7D&RecNum=RecNum&SignName=HaYiiRo&TemplateCode=TemplateCode";
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        var_dump(curl_exec($curl));
    }
}